/**
 * 
 */
package edu.pw.treegrid.server.filter;

import java.util.Set;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import edu.pw.treegrid.server.query.ColumnNode;
import edu.pw.treegrid.server.query.QueryTree;
import edu.pw.treegrid.server.reportmodel.Report;
import edu.pw.treegrid.server.reportmodel.ReportColumn;

/** 
 * @author Piotrek
 */
public abstract class SimpleFilter implements Filter {
	private static Logger log = Logger.getLogger("xalan.reports");
	
	private static final String COLUMN_ATTRIBUTE = "column";
	private static final String VALUE_ATTRIBUTE = "value";
	
	protected Object value;

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	private ReportColumn reportColumn;

	public ReportColumn getReportColumn() {
		return reportColumn;
	}

	public void setReportColumn(ReportColumn reportColumn) {
		this.reportColumn = reportColumn;
	}
	
	public void addParameter(QueryTree queryTree, Object value) {
		queryTree.addParameter(value);
	}
	
	public Element serializeToXML(Document document) {
		Element element = document.createElement(getXMLElementName());
		element.setAttribute(COLUMN_ATTRIBUTE, this.reportColumn.getName());
		element.setAttribute(VALUE_ATTRIBUTE, this.value.toString());		
		return element;
	}
	
	public void deserializeFromXML(Element filterElement,
			Report report) {
		String columnId = filterElement.getAttribute(COLUMN_ATTRIBUTE);
		this.reportColumn = report.getColumnByName(columnId);
		if(reportColumn == null) {
			log.warn("Kolumna w filtrze nie istnieje [" + columnId + "]");
		}
		this.value = filterElement.getAttribute(VALUE_ATTRIBUTE);
	}
	
	public void generateWhere(QueryTree queryTree, StringBuilder sb) {
		Set<ColumnNode> nodes = queryTree.getColumnNodesForReportColumn(this
				.getReportColumn());
		for (ColumnNode cn : nodes) {
			if((nodes.size() == 2 && !cn.isIdColumn()) || nodes.size() == 1) {
				sb.append(cn.getBaseExpressionString());
				sb.append(" ");
				sb.append(this.getOperatorType().getOperator());
				sb.append(" ?");
				this.addParameter(queryTree, this.getValue());
			}
		}
	}
	
	@Override
	public String getXMLElementName() {
		return getOperatorType().toString();
	}
	
	public abstract OperatorType getOperatorType();
}